import {IFieldRes, exp} from "./exp";

declare function require(str: string): any;

if (typeof window === "undefined") {
    let mong = "mongodb";
    var ObjectID = require(mong).ObjectID
}
export class mongo {
    static backUpTable = "_back"

    static newID(): any {
        return new ObjectID();
    }

    /**
     * @装饰objectID类型数据验证
     * @param msg 验证失败提示
     * @returns {function(Object, string): undefined}
     */
    static objectID(msg?: string) {
        return (target: Object, propertyKey: string) => {
            exp.setFieldCheckMetaData<any>(target.constructor, propertyKey, obj => {
                let ret = false;

                if (obj.val != null && ObjectID.isValid(obj.val)) {
                    obj.val = new ObjectID(obj.val);
                    ret = true;
                }

                if (msg)
                    obj.msg = msg;

                return ret;
            });
        }
    }

    static stringObjectID(func?: (num: IFieldRes<string>) => boolean, msg?: string) {
        return (target: Object, propertyKey: string) => {
            exp.setFieldCheckMetaData<any>(target.constructor, propertyKey, obj => {
                let ret = true;

                if (obj.val != null && obj.val != "") {
                    obj.val = obj.val + "";
                    if (ObjectID.isValid(obj.val)) {
                        ret = true;
                    }
                    else {
                        ret = false;
                    }
                }
                else {
                    obj.val = obj.defaul;
                }

                if (msg)
                    obj.msg = msg;

                if (func)
                    ret = func(obj);

                return ret;
            });
        }
    }


    /**
     * @装饰objectID类型数据验证
     * @param msg 验证失败提示
     * @returns {function(Object, string): undefined}
     */
    static objectIDnullAble(msg?: string) {
        return (target: Object, propertyKey: string) => {
            exp.setFieldCheckMetaData<any>(target.constructor, propertyKey, obj => {
                let ret = true;
                if (obj.val == null) {
                }
                else {
                    if (ObjectID.isValid(obj.val)) {
                        obj.val = new ObjectID(obj.val);
                    }
                    else {
                        obj.val = null;
                    }
                }
                if (msg)
                    obj.msg = msg;

                return ret;
            });
        }
    }


    ///////////
}

if (typeof window !== "undefined") {
    mongo.newID = () => {
        return "" as any;
    }
}